﻿using Crossroad.Core.Exceptions;
using Crossroad.OAuth.Attributes;
using Crossroad.System.Admin.Model;
using Crossroad.System.Admin.Service;
using Crossroad.System.Admin.Service.Impl;
using Crossroad.System.Api;
using Crossroad.Utils.Extensions;
using Microsoft.AspNetCore.Mvc;

namespace Crossroad.System.Admin.Controller
{
    /// <summary>
    /// 角色与菜单操作的关联
    /// </summary>
    [ApiAuthorize]
    [Route("api/system/admin/role/menu-options")]
    public class RoleJoinMenuOptionController : BaseApi
    {
        /// <summary>
        /// 角色与菜单操作的关联 service
        /// </summary>
        private readonly RoleJoinMenuOptionService rmoService;

        public RoleJoinMenuOptionController(
            IRoleJoinMenuOptionService rmoServiceIpt
        )
        {
            rmoService = rmoServiceIpt as RoleJoinMenuOptionService;
        }


        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuId"></param>
        /// <param name="optionId"></param>
        /// <returns></returns>
        [HttpGet]
        public object GetList(
            int? roleId = null,
            int? menuId = null,
            string optionId = null
        )
        {
            return rmoService.GetList(queryable =>
            {
                if (roleId.NotContent())
                    queryable.Where(a => a.roleId == roleId.Value);
                if (menuId.NotContent())
                    queryable.Where(a => a.menuId == menuId.Value);
                if (optionId.NotContent())
                    queryable.Where(a => a.optionId.Equals(optionId));
            });
        }

        /// <summary>
        /// 新增一个角色与菜单操作的关联
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        [HttpPost]
        public object CreateAt(
            [FromBody] RoleJoinMenuOption parameter
        )
        {
            rmoService.DeleteBatch(parameter);
            rmoService.CreateAt(parameter);

            return true;
        }

        /// <summary>
        /// 删除一个角色与菜单操作的关联
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete]
        public object DeleteAt(
            int? roleId,
            int? menuId,
            string optionId
        )
        {
            if(roleId.NotContent())
                throw new LogicException("角色id不能为空!");
            if(menuId.NotContent())
                throw new LogicException("菜单id不能为空!");
            if(optionId.IsNullOrEmpty())
                throw new LogicException("操作id不能为空!");

            rmoService.DeleteAt(new RoleJoinMenuOption
            {
                roleId = roleId.Value,
                menuId = menuId.Value,
                optionId = optionId
            });

            return true;
        }


    }
}
